import 'package:flutter/material.dart';
import 'package:labcloud_app/api/product/product_service.dart';
import 'package:labcloud_app/datas/page_vo.dart';
import 'package:labcloud_app/datas/product.dart';

class ProductModel extends ChangeNotifier {

  List<Product>? _productList =  [];

  bool _isLoading = false;
  String? _errorMessage;

  num _currentPage = 1;
  num _pageSize = 4;
  num _totalPages = 0;
  num _total = 0;
  bool _hasNextPage = false;

  bool get hasNextPage => _hasNextPage;
  num get totalPages => _totalPages;
  num get total => _total;
  List<Product>? get productList => _productList;
  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;
  num get currentPage => _currentPage;
  num get pageSize => _pageSize;

  /// 加载产品列表数据（第一页）
  Future<void> loadProductList({page = 1 , size = 4}) async {
    if (_isLoading) return;

    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final response = await ProductApiService.getList(
        page: page,
        size: size,
      );
      
      if (response.statusCode == 200) {
        // 解析分页数据
        var _pageVO = PageVO.fromJson(response.data);
        _currentPage = _pageVO.page!;
        _totalPages = _pageVO.totalPage!;
        _total = _pageVO.total!;
        _hasNextPage = _currentPage < _totalPages;
        // 提取产品列表数据
        if (_pageVO.data != null) {
          print(_pageVO.data);
          _pageVO.data.forEach((item) {
            var prod = Product.fromJson(item);
            _productList?.add(prod);
          });
        }
      } else {
        _errorMessage = '加载失败，状态码: ${response.statusCode}';
      }
    } catch (e) {
      _errorMessage = '加载失败: $e';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 加载下一页
  Future<void> loadNextPage() async {
    if (!hasNextPage || _isLoading) return;
    _currentPage++;
    await loadProductList(page: _currentPage, size: _pageSize);
  }


  /// 清除数据
  void clear() {
    _productList = null;
    _errorMessage = null;
    notifyListeners();
  }
}
